
const EnvContext = require('../../../../common/context/EnvContext')
const { uuid } = require('../../../../common/utils/uuidUtil')
const pushEvent = "__PUBLISH_PUSH__"
const { BrowserWindow, webContents } = require('electron');

exports.onEmit = function (eventName, payload, theWin) {
    const msgInfo = {
        msgId: uuid(),
        topic: eventName,
        body: payload,
        gmtEvent: new Date(),
        success: true,
        broadcast: true,
    }
    if (theWin) {
        // 广播消息给指定渲染进程
        theWin.webContents.send(eventName, msgInfo)
        // 广播消息给指定渲染的所有view
        theWin.getBrowserViews().map(view => {
            createAsyncTask(view.webContents.send(eventName, msgInfo))
        })

    } else {
        webContents.getAllWebContents().map(webContent => {

            createAsyncTask(webContent.send(eventName, msgInfo))
        })
    }

}

function createAsyncTask(syncTask) {
    return Promise.resolve(syncTask).then();
}



exports.getOn = function () {
    return EnvContext.getInstance().getEmitter().on
}

exports.getOnce = function () {
    return EnvContext.getInstance().getEmitter().once
}


exports.getOff = function () {
    return EnvContext.getInstance().getEmitter().removeAllListeners
}

